import { getUserInfo, login } from '@/api/user'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {}
}
const mutations = {
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  clearToken(state, payload) {
    state.token = null
    removeToken()
  },
  clearUserInfo(state, payload) {
    state.userInfo = {}
  }
}
const actions = {
  async getToken({ commit }, data) {
    // console.log(data)
    const res = await login(data)
    commit('setToken', res)
    console.log(res)
  },
  async getUserInfo({ commit }) {
    // setTimeout(() => {
    //   commit('setUserInfo', { name: '张三' })
    // }, 2000)
    const res = await getUserInfo()
    commit('setUserInfo', res)
    console.log(res)
  },
  // 多个mutations 提交要用1个action包裹起来 有些更严格甚至 页面中不允许提交mutation 只能提交action
  logout({ commit }) {
    commit('clearToken')
    commit('clearUserInfo')
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
/*
点击登录:
1. 请求后端接口
2. 拿到token 存本地(持久化)
3. 成功提示
4. 页面跳转

实际开发中:
token既要存localStorage  也要存vuex(数据共享/响应式)
    state:  token
    mutation:  更新token
    action: 发登录请求

分析:
token  存下来(因为将来请求都需要带token  必须找一个一直可以保存的地方localStorage)

*/
